<script setup lang='ts'>
import {ref, onMounted} from 'vue'
import type {Ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {login} from '../../api/user'
import { showToast,showDialog } from 'vant';

import { useUserStore } from '../../stores/user'

// 获取全局状态中的属性和方法
const user = useUserStore()

const loginname: Ref<string> = ref('')
const password: Ref<string> = ref('')

const route = useRoute()
const router = useRouter()

// 生命周期
onMounted(()=>{
  console.log(route.query.code, user);
})

function onSubmit(){
  // 做登录的数据提交
  login({
    loginname: loginname.value,
    password: password.value
  }).then(res => {
    // console.log(res);
    if(res.data.code == 200){

      // 保存用户的登录信息
      showToast('登录成功了')
      
      // 保存在本地
      localStorage.setItem('userid', res.data.data.userid)
      localStorage.setItem('token', res.data.data.token)
      localStorage.setItem('loginState', 'true')
      // 存到全局状态中
      user.changeUserState({
        loginState: true,
        userid: res.data.data.userid,
        token: res.data.data.token
      })

      if (route.query.code == '10086') {
          // 注册页面来的，登录成功就要去首页
          router.push('/')
      }else {
          router.back()
      }
    }else {
      // 登录有问题
      showDialog({ message: res.data.message });
    }
  })
}

function backFn(){
  // if (route.query.code == 10086) {
  //   // 注册页面来的，登录成功
  //   router.push('/')
  // }else {
    router.back()
  // }
}

</script>
<template>
  <main class="box">
    <header class="header">
      <!-- <van-nav-bar
          title="登录"
          left-text="返回"
          left-arrow
          @click-left="$router.back()"
        /> -->

      <van-icon @click="backFn" class="left-icon" name="arrow-left" />
      登录
    </header>

    <div class="content">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="loginname"
            name="用户名"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div style="margin: 16px">
          <van-button round block color='#f66' native-type="submit">
            登录
          </van-button>
        </div>
        <div style="margin: 16px">
          <van-button @click="$router.push('/register')" round block type='success'>
            去注册
          </van-button>
        </div>
      </van-form>
    </div>
  </main>
</template>
<style scoped lang="scss">
.left-icon {
  float: left;
  line-height: 0.44rem;
  margin-left: 16px;
}
.content {
  padding-top: 30px;

  box-sizing: border-box;
}
</style>